package com.qianlima.upload.domain.service;

import com.qianlima.upload.common.dto.FileDto;
import com.qianlima.upload.infrastructure.core.config.FileGlobalConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @description: 文件上传服务
 * @author：allms
 * @date: 2023/3/22 15:08
 */
@Component
public class FileUploadExec {

    @Autowired
    private List<IFileService> fileServiceList;
    @Autowired
    protected FileGlobalConfiguration fileGlobalConfiguration;

    private IFileService getFileUploadType() {
       return fileServiceList.stream()
                .filter(fileService -> fileService.getType().equals(fileGlobalConfiguration.getType()))
                .findFirst().orElseThrow(RuntimeException::new);
    }


    /**
     * 上传普通文件
     *
     * @param multipartFileList 文件列表
     * @return
     * @throws IOException
     */
    public List<String> upload(List<MultipartFile> multipartFileList) throws IOException{
        IFileService fileService = getFileUploadType();
        return fileService.upload(multipartFileList);
    }

    /**
     * 大文件上传，分片上传
     *
     * @param fileDto 文件信息
     * @param file    文件
     * @param isFile  是否文件
     * @return 返回文件路径
     * @throws IOException
     * @throws InterruptedException
     */
    public String fragUpload(FileDto fileDto, boolean isFile, MultipartFile file) throws IOException, InterruptedException{
        IFileService fileService = getFileUploadType();
        return fileService.fragUpload(fileDto, isFile, file);
    }

    /**
     * 检查分片
     *
     * @param key        分片key
     * @param shardTotal 分片总大小
     * @return 文件信息
     */
    public FileDto checkFrag(String key, Integer shardTotal){
        IFileService fileService = getFileUploadType();
        return fileService.checkFrag(key, shardTotal);
    }

}
